
#include "udpServer.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <signal.h>
using namespace std;
using namespace server;

#include "Dictionary.hpp"
#include "onlineUsers.hpp"

void Usage(char *command)
{
    cout << "\nUsage:\n\t" << command << "\t" << "server_port\n" << endl; 
}


Dictionary dict;
void reload(int signo)
{
    dict.loadFile();
}
void translateDemo(int _socketFd,struct sockaddr_in &client,string &message)
{
    dict.loadFile();
    string response = dict.translate(message);
    sendto(_socketFd,response.c_str(),response.size(),0,(struct sockaddr *)&client,sizeof(client));
}

void shellDemo(int _socketFd,struct sockaddr_in &client,string &command)
{
    string response;
    FILE *fp = popen(command.c_str(),"r");
    if(fp == nullptr) response = command + " exec fail";

    char line[1024];
    while(fgets(line,sizeof(line),fp))
    {
        response += line;
    }
    pclose(fp);

    cout << response << endl;
    sendto(_socketFd,response.c_str(),response.size(),0,(struct sockaddr *)&client,sizeof(client));
}

onlineUsers ous;
void chatDemo(int _socketFd,struct sockaddr_in &client,string &message)
{
    string ip = inet_ntoa(client.sin_addr);
    uint16_t port = ntohs(client.sin_port);
    if(message == "online") ous.addUser(ip,port);
    if(message == "offline") ous.delUser(ip,port);

    if(ous.isOnline(ip,port))
    {
        ous.routingMessage(_socketFd,ip,port,message);
    }
    else 
    {
        string response = "please online...";
        sendto(_socketFd,response.c_str(),response.size(),0,(struct sockaddr *)&client,sizeof(client));
    }
}

/*服务器启动时只需要绑定端口号*/
int main(int argc,char *argv[])
{
    //signal(2,reload);
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(START_ERROR);
    }
    uint16_t port = atoi(argv[1]);
    
    unique_ptr<udpServer> upus(new udpServer(chatDemo,port));
    upus->start();
    return 0;
}